let http = require('http');
// var fs = require('fs');
let url = require('url');

class HttpServer {
	constructor(port, crossDomain="*") {
		this.port = port;
		this.crossDomain = crossDomain;
	}
	startWork(requestCallback) {
		let self = this;
		this.server = http.createServer(function (request, response) {
			if (requestCallback) {
				response.setHeader('Access-Control-Allow-Origin', self.crossDomain);
				response.send = function (num,str=null) {
					this.writeHead(num, { 'Content-Type': 'text/html' });
					if (str) {
						this.write(str);
					}
					this.end();
				}
				let u = url.parse(request.url,true);
				if (request.method==="POST") {
					request.on('data', function (chunk) {
						requestCallback(request, response, u, chunk);
					});
				} else {
					requestCallback(request, response, u, null);
				}
			} else {
				response.writeHead(404, { 'Content-Type': 'text/html' });
				response.end();
			}
		});
		this.server.on("listening", function () {
			if (global.log) {
				global.log.print(`port:${self.port} httpserver listening...`);
			} else {
				console.log(`port:${self.port} httpserver listening...`);
			}
		})
		this.server.on("error", function () {
			if (global.log) {
				global.log.error("httpserver error " + err);
			} else {
				console.error("httpserver error " + err);
			}
		})
		this.server.setTimeout(3000);
		this.server.listen(this.port);
	}
	close() {
		if (this.server) {
			this.server.close();
		}
	}
}

// let httpsvr = new HttpServer(8005);
// httpsvr.startWork(null);

module.exports = HttpServer;